from flask import Blueprint, current_app, render_template, request

from storm.locals import *
import urllib
import sys
from storm.tracer import debug
from mysrv.models.video import *

frontend = Blueprint("frontend", __name__)
app = current_app
@frontend.route("/")
def index():
    app.logger.debug("request the path /")
    return "ok"

@frontend.route("/hello")
def hello():
    app.logger.debug("request the path /")
    return "hello, world"

@frontend.route("/test")
def t():

    start = int(request.values.get("start", 0))
    count = 40
    debug(True, stream=sys.stdout)
    db_cfg = current_app.config.get("DB_CONFIG1")
    uri = "mysql://%s:%s@%s/%s?charset=utf8" % (
            urllib.quote(db_cfg["user"]),
            urllib.quote(db_cfg["passwd"]),
            db_cfg["host"],
            db_cfg["db"]
        )
    db = create_database(uri)
    store = Store(db)
    origin=[MovieNames, 
            Join(UserInfo, UserInfo.terminalid == MovieNames.terminalid),
            Join(Devinfo, Devinfo.serial == UserInfo.deviceid),
            ]
    r = store.using(*origin).find((MovieNames, UserInfo, Devinfo)
            #, Devinfo.id < 20
            ).order_by(Desc(MovieNames.watch_time))[start:count+start]
    return render_template("t.html", r = r, next = start + count, counter = start)
